package org.ru.mse10.cvis.service.search;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.ru.mse10.cvis.dto.cv.CustomFieldDTO;
import org.ru.mse10.cvis.entity.cv.custom.CustomField;
import org.ru.mse10.cvis.entity.util.CustomFieldType;
import org.ru.mse10.cvis.util.BooleanSelection;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class CustomFieldSearcher.
 */
public class CustomFieldSearcher extends
		EntitySearcher<CustomField, CustomFieldDTO> {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.ru.mse10.cvis.service.search.EntitySearcher#appendCriteria(javax.
	 * persistence.criteria.CriteriaBuilder,
	 * javax.persistence.criteria.CriteriaQuery,
	 * javax.persistence.criteria.Root, org.ru.mse10.cvis.dto.BaseDTO)
	 */
	@Override
	protected <X> void appendCriteria(CriteriaBuilder qb, CriteriaQuery<X> c,
			Root<CustomField> p, CustomFieldDTO dto) {
		List<Predicate> criteria = new ArrayList<Predicate>();
		if (!CommonUtil.isEmpty(dto.getDisplayName())) {
			criteria.add(qb.like(p.<String> get("displayName"),
					"%" + dto.getDisplayName() + "%"));
		}
		if (!CommonUtil.isEmpty(dto.getIdentifier())) {
			criteria.add(qb.like(p.<String> get("fieldKey"),
					"%" + dto.getIdentifier() + "%"));
		}
		if (!CommonUtil.isEmpty(dto.getTypes())) {
			In<CustomFieldType> in = qb
					.in(p.<CustomFieldType> get("fieldType"));
			for (CustomFieldType type : dto.getTypes()) {
				in.value(type);
			}
			criteria.add(in);
		}
		if (BooleanSelection.BOTH != dto.getRequired()) {
			boolean selection = BooleanSelection.TRUE == dto.getRequired() ? true
					: false;
			criteria.add(qb.equal(p.<Boolean> get("required"), selection));
		}
		c.where(criteria.toArray(new Predicate[] {}));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.ru.mse10.cvis.service.search.EntitySearcher#getEntityClass()
	 */
	@Override
	public Class<CustomField> getEntityClass() {
		return CustomField.class;
	}
}
